#!/bin/sh
# filename: dmenubg-v1.sh, use feh
# deploy filename: dmenubg
# --------------------------
# Configuration
# --------------------------
PICTURES_DIR="${HOME}/Pictures"  # Your images folder (no ~, no quotes)
DMENU_PROMPT="Select Background: "  # Prompt text (simple, no extra quotes)

# --------------------------
# Step 1: Check dependencies (dmenu + feh)
# --------------------------
if ! command -v dmenu >/dev/null 2>&1; then
    echo "❌ Error: 'dmenu' is not installed. Please install it first." >&2
    exit 1
fi
if ! command -v feh >/dev/null 2>&1; then
    echo "❌ Error: 'feh' is not installed (required to set background). Please install it first." >&2
    exit 1
fi

# --------------------------
# Step 2: Check if Pictures directory exists
# --------------------------
if [ ! -d "${PICTURES_DIR}" ]; then
    echo "❌ Error: Pictures directory '${PICTURES_DIR}' does not exist." >&2
    exit 1
fi

# --------------------------
# Step 3: List ONLY image files (space-safe, case-insensitive)
# Supported: jpg, jpeg, png, gif, bmp, webp, svg
# --------------------------
list_images() {
    find "${PICTURES_DIR}" -maxdepth 1 -type f \
        \( -iname "*.jpg"  -o -iname "*.jpeg" -o -iname "*.png"  \
        -o -iname "*.gif"  -o -iname "*.bmp"  -o -iname "*.webp" \
        -o -iname "*.svg" \) \
        | sed "s|^${PICTURES_DIR}/||"  # Show only filenames (no full paths)
}

# --------------------------
# Step 4: Pipe images to dmenu (NO extra style flags)
# --------------------------
selected_filename=$(list_images | dmenu -i -p "${DMENU_PROMPT}" "$@")

# Exit if no selection (user pressed Esc)
if [ -z "${selected_filename}" ]; then
    echo "ℹ️ No image selected. Exiting."
    exit 0
fi

# --------------------------
# Step 5: Get full path to selected image
# --------------------------
selected_path="${PICTURES_DIR}/${selected_filename}"

# --------------------------
# Step 6: Validate file exists
# --------------------------
if [ ! -f "${selected_path}" ]; then
    echo "❌ Error: Image '${selected_path}' no longer exists." >&2
    exit 1
fi

# --------------------------
# Step 7: Set background with feh
# --------------------------
feh --bg-scale "${selected_path}"  # Scales image to fit screen (preserves aspect ratio)

# --------------------------
# Step 8: Confirm success
# --------------------------
echo "✅ Success! Background set to: ${selected_path}"
